package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.TitleBar;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.empty.IntegralBean;
import com.zhsj.OkeHomeConsumption.empty.RetrunBean;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.RetrunPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.RetrunUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.MinewalletActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.jifenActivity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 返还额度
 */
public class RetrunActivity extends MyActivity implements RetrunUIInterFace {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private ArrayList<RetrunBean> retrunBeans;

    private ArrayList<RetrunBean> retrunBeanLists;

    private ArrayList<IntegralBean> mIntegrallist;
    private ArrayList<IntegralBean> mIntegrallists;

    private RetrunPresenter retrunPresenter;
    private RecyclerView retrun_recycleview;
    private RetrunAdapter retrunAdapter;
    private ItemShopAdapter shopadper;
    private TextView retrun_txt;
    private TitleBar retrun_titile;
    private FormalUserInfo userInfo = null;
    private Button duihuan_text;
    private  int title_flage = -1;
    //审核状态
    private String kyc_status;
    //钱包状态
    private String stat_user;

    private String fanhuan_price;
    private int pageIndex = 1;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_retrun;
    }

    @Override
    protected int getTitleId() {
        return R.id.retrun_titile;
    }

    @Override
    protected void initView() {
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        duihuan_text = findViewById(R.id.duihuan_text);
        retrun_txt = findViewById(R.id.retrun_txt);
        retrun_titile = findViewById(R.id.retrun_titile);
        retrunPresenter = new RetrunPresenter(this, this);
        retrun_recycleview = findViewById(R.id.retrun_recycleview);
        retrunBeans = new ArrayList<>();
        retrunBeanLists= new ArrayList<>();
        mIntegrallist = new ArrayList<>();
        mIntegrallists= new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(this);
        retrun_recycleview.setLayoutManager(manager);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
         title_flage = intent.getIntExtra("title_flage", 0);
        fanhuan_price = intent.getStringExtra("fanhuan_price");
        refreshLayout.setEnableRefresh(false);//是否启用下拉刷新功能
        initRefersh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);//传入false表示刷新失败
//                if (orderBeanList != null && orderBeanList.size() > 0) {
//                    orderBeanList.clear();
//                }
//                refreshLayout.setRefreshing(false);
                initRefersh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                NextPost();
            }
        });

    }

    public void initRefersh() {
        if (title_flage == 0) {

            retrun_titile.setTitle("返还额度");
            retrun_txt.setText("返还额度:" + fanhuan_price);
            retrunPresenter.RetrunListPost(pageIndex, 10);
        } else {
            duihuan_text.setVisibility(View.VISIBLE);
            retrun_titile.setTitle("积分列表");
            retrun_txt.setText("积分:" + fanhuan_price);
            //用户积分查询
            retrunPresenter.Integrals(pageIndex);
            duihuan_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    IsWalletUser(userInfo.getId() + "", "RSA");
                }
            });

        }
    }

    public void NextPost() {
        pageIndex++;
        initRefersh();
    }

    //返还额度
    @Override
    public void RetrunListPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                JSONArray arr = jsonobj.optJSONArray("jsonObj");
                retrunBeans = new Gson().fromJson(arr.toString(), new
                        TypeToken<ArrayList<RetrunBean>>() {
                        }.getType());
                retrunBeanLists.addAll(retrunBeans);
                if(pageIndex!=1){
                    if(retrunBeans.size()!=0){
                        retrunAdapter.notifyDataSetChanged();
                    }else{
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }else{
                    retrunAdapter = new RetrunAdapter(retrunBeanLists, this);
                    retrun_recycleview.setAdapter(retrunAdapter);
                }

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("ShopListPost", "获取返还余额列表");
        }
    }

    //积分列表
    @Override
    public void Integrals(String context) {
        LogUtils.e("积分列表", context);
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                JSONArray arr = jsonobj.optJSONArray("jsonObj");
                mIntegrallist = new Gson().fromJson(arr.toString(), new
                        TypeToken<ArrayList<IntegralBean>>() {
                        }.getType());
                mIntegrallists.addAll(mIntegrallist);

                if(pageIndex!=1){
                    if(mIntegrallist.size()!=0){
                        shopadper.notifyDataSetChanged();
                    }else{
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }else{
                    shopadper = new ItemShopAdapter(mIntegrallists);
                    retrun_recycleview.setAdapter(shopadper);
                }

                //设置Adapter


            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("Integrals", "积分列表");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    private class RetrunAdapter extends RecyclerView.Adapter<RetrunAdapter.ViewHolder> {

        private ArrayList<RetrunBean> dealListBeans;
        private Context context;


        public RetrunAdapter(ArrayList<RetrunBean> dealListBeans, Context context) {
            this.dealListBeans = dealListBeans;
            this.context = context;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.activity_retrun_item, null);
            ViewHolder viewHolder = new ViewHolder(inflate);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
            RetrunBean retrunBean = dealListBeans.get(i);
            if (retrunBean.getCreateDate() != null) {
                viewHolder.retrun_price.setText(String.valueOf(retrunBean.getBackAmount()));
                viewHolder.retrun_show.setText(retrunBean.getBackAmountText());
                viewHolder.retrun_time.setText(retrunBean.getCreateDate());
            }
        }

        @Override
        public int getItemCount() {
            return retrunBeanLists.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            private TextView retrun_show;
            private TextView retrun_time;
            private TextView retrun_price;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                retrun_time = itemView.findViewById(R.id.retrun_time);
                retrun_price = itemView.findViewById(R.id.retrun_price);
                retrun_show = itemView.findViewById(R.id.retrun_show);
            }
        }
    }


    public class ItemShopAdapter extends BaseQuickAdapter<IntegralBean, BaseViewHolder> {

        public ItemShopAdapter(@Nullable List<IntegralBean> data) {
            super(R.layout.activity_retrun_item, data);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, final IntegralBean item) {
            helper.setText(R.id.retrun_show, item.getIntegralText2())
                    .setText(R.id.retrun_time, item.getCreateDate());
            if (item.getIntegral() > 0) {
                helper.setText(R.id.retrun_price, "+" + item.getIntegral())
                        .setTextColor(R.id.retrun_price, getResources().getColor(R.color.orange));
            } else {
                helper.setText(R.id.retrun_price, String.valueOf(item.getIntegral()))
                        .setTextColor(R.id.retrun_price, getResources().getColor(R.color.black));
            }

        }
    }

    //是否是钱包用户
    public void IsWalletUser(final String user_id, String sign_type) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("sign_type", sign_type);

//        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("user_id", user_id);
        paramMaps.put("sign_type", sign_type);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.IS_WALLET_USER, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                TimeOutHandler.pDialogUtils = null;
                try {
//                    LogUtils.e("content_判断是否钱包用户", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject singleuserquery = jsonObject.optJSONObject("singleuserquery");
                        String ret_code = singleuserquery.optString("ret_code");
                        kyc_status = singleuserquery.optString("kyc_status");
                        stat_user = singleuserquery.optString("stat_user");
                        if ("0000".equals(ret_code)) {
                            if ("1".equals(kyc_status) || "4".equals(kyc_status) || "2".equals(stat_user) || "1".equals(stat_user)) {
                                startActivity(new Intent(getActivity(), jifenActivity.class).putExtra("fanhuan_price", fanhuan_price));

                            }
                        } else if ("3".equals(kyc_status)) {
                            toast("您已提交钱包开户，请耐心等待");
                        } else {
                            startActivity(MinewalletActivity.class);
                        }
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                        }
                    } else {
                        if (!message.equals("null")) {
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override

            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }
}
